package com.example.gateway1.ft;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class MyGlobalFileter implements GlobalFilter, Ordered {


    /**
     * 自定义过滤器规则
     * //  获取请求头信息
     * HttpHeaders headers = exchange.getRequest().getHeaders();
     * String first = exchange.getRequest().getHeaders().getFirst("Content-type");
     * ServerHttpRequest build = exchange.getRequest().mutate().header("Content-type","json").build();
     * //  获取请求方式
     * String name = exchange.getRequest().getMethod().name();
     * //  获取请求URL地址信息
     * String host = exchange.getRequest().getURI().getHost();
     * String path1 = exchange.getRequest().getURI().getPath();
     * String rawPath = exchange.getRequest().getURI().getRawPath();
     * //  获取请求属性信息
     * exchange.getAttributes().put("startTime",123123);
     * Long startTime1 = exchange.getAttribute("startTime");
     * //  获取返回体
     * ServerHttpResponse response = exchange.getResponse();
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        System.out.println("-----------------全局过滤器MyGlobalFilter---------------------");
//        String token = exchange.getRequest().getQueryParams().getFirst("token");
//        if (StringUtils.isBlank(token)) {
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();//拦截
//        }
        return chain.filter(exchange); //放行
    }

    /**
     * 定义过滤器执行顺序
     * 返回值越小，越靠前执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
